//
//  LspNbNetWorkManage.swift
//  LspSwiftFinayTest
//
//  Created by lsp's mac pro on 2018/4/12.
//  Copyright © 2018年 lsp's mac pro. All rights reserved.
//

import UIKit

//swift的枚举支持任何数据类型
enum LspNbHTTPChoice {
    case GET
    case POST
}
//access_token
//2.00JJ9PZC0b16kkf2abc1dff4wts72B

class LspNbNetWorkManage: AFHTTPSessionManager {

    //网络单例
    static let shared: LspNbNetWorkManage = {
        let instance = LspNbNetWorkManage()
        
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
    }() 
    
    //微博用户model
    lazy var userModel = LspNbUserAccount()
    
    
    var userLogan:Bool{

        return userModel.access_token != nil
    }
//
    
    //封装一个带token的网络请求
    func tokenRequest(Method:LspNbHTTPChoice = .GET, URLString: String,parameters: [String: AnyObject]?, completed: @escaping ((_ json: AnyObject?, _ isSuccess: Bool)->()))  {
        
        //guard let 守护判断token 是否为空
        guard let token = userModel.access_token else {
            // 发送通知（本方法不知道是谁调用，谁接收到通知谁处理）
            print("没有token 需要登录")
            
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: lspNbSwiftUserShouldLogin), object: self, userInfo: nil)
            
            
            completed(nil, false)
            return
        }
        var parameters = parameters
        if parameters==nil {
            parameters = [String:AnyObject]()
        }
        parameters!["access_token"] = token as AnyObject
        request(URLString: URLString, parameters: parameters, completed: completed)
        
    }
    
    /// 封装网络请求方法
    ///
    /// - Parameters:
    /// - Method: GET/POST, 默认是GET请求
    /// - URLString: 请求地址
    /// - parameters: 参数
    /// - completed: 结束回调
    
    func request(Method:LspNbHTTPChoice = .GET, URLString: String,parameters: [String: AnyObject]?, completed:@escaping ((_ json: AnyObject?, _ isSuccess: Bool)->())) {
        
        /// 定义成功回调闭包
        let success = { (task: URLSessionDataTask,json: Any?)->() in
            completed(json as AnyObject?,true)
        }
        
        /// 定义失败回调闭包
        
        /// 对于测试用户（应用程序还没有提交给新浪微博审核）每天刷新量是有限的
        
        /// 超出上限token 会被锁定
        
        /// 如果超出上限  被锁定 可以新建一个应用程序
        let failure = {(task: URLSessionDataTask?, error: Error)->() in
            if (task?.response as? HTTPURLResponse)?.statusCode==403 {
                print("token 过期了")
                //  发送通知（本方法不知道是谁调用，谁接收到通知谁处理）
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: lspNbSwiftUserShouldLogin), object: self, userInfo:["sb":"jb"])
            }
            completed(nil,false)
        }
        
        /// 通过请求方法,执行不同的请求
        // 如果是 GET 请求
        if Method == .GET { // GET
            
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
            
        } else { // POST
            
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
}
